package cn.edu.buu.news.service.impl;

import cn.edu.buu.news.entity.LearningPath;
import cn.edu.buu.news.mapper.LearningPathMapper;
import cn.edu.buu.news.service.LearningPathService;
import cn.edu.buu.news.vo.PageQuery;
import cn.edu.buu.news.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class LearningPathServiceImpl implements LearningPathService {

    @Autowired
    private LearningPathMapper learningPathMapper;

    @Override
    public void add(LearningPath learningPath) {
        learningPathMapper.insert(learningPath);
    }

    @Override
    public void deleteById(Long id) {
        learningPathMapper.deleteById(id);
    }

    @Override
    public void update(LearningPath learningPath) {
        learningPathMapper.update(learningPath);
    }

    @Override
    @Transactional(readOnly = true)
    public LearningPath findById(Long id) {
        return learningPathMapper.selectById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public List<LearningPath> findAll() {
        return learningPathMapper.selectAll();
    }

    @Override
    @Transactional(readOnly = true)
    public PageResult<LearningPath> findByPage(PageQuery query) {
        // 校验page和size，避免负数或0
        int page = query.getPage() < 1 ? 1 : query.getPage();
        int size = query.getSize() < 1 ? 10 : query.getSize();
        int offset = (page - 1) * size;

        List<LearningPath> list = learningPathMapper.selectByPage(query, offset);
        Long total = learningPathMapper.selectCount(query);
        return new PageResult<>(list, total);
    }
}